package cuser.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import cuser.doman.CMember;
import cuser.doman.LoginForm;
import cuser.mapper.CMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 弔人
 * @time: 2022/11/7 9:27
 */
@Service
public class UserService {
    @Autowired
    private CMemberMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public AjaxResult login(LoginForm loginForm) {
        //查看用户是否存在
        List<CMember> userEntityList = userMapper.selectListByUserName(loginForm.getLoginName());
        //结合为空就是不存在
        if (CollectionUtils.isNotEmpty(userEntityList)){
            CMember userEntity = userEntityList.get(0);
            if (userEntity!=null){
                //用户名存在  判断密码
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                boolean matches = encoder.matches(loginForm.getPassword(), userEntity.getPassword());
                if (matches){
                    //登陆成功
                    //jwt生成token
                    Map<String, Object> map = new HashMap<>();
                    Long userId = userEntity.getId();
                    map.put("userId", String.valueOf(userId));
                    map.put("userName", userEntity.getUsername());
                    String token = JwtUtils.createToken((HashMap<String, Object>) map);

                    //存入redis五分钟
                    redisTemplate.opsForValue().set("token_"+userId, token ,5 , TimeUnit.MINUTES);

                    return new AjaxResult(1,  token, map);
                }else {
                    //密码错误
                    return new AjaxResult(0, "用户名不存在或者密码错误", null);
                }
            }else {
                return new AjaxResult(0, "用户名不存在或者密码错误", null);
            }
        }else {
            return new AjaxResult(0, "用户名不存在或者密码错误", null);
        }



    }
}
